package cs.utils;

import java.sql.*;

public class JDBCUtils {

    private static JDBCUtils jdbcUtils;

    /**
     * 获取数据库连接
     */
    public static Connection getDb() {
        //数据库连接字符串初始化
        String url = "jdbc:mysql://localhost:3306/wages";
        //数据库的用户
        String uname = "root";
        //数据库密码
        String upassword = "123456";

        //返回数据库连接对象
        return getConnection(url, uname, upassword);
    }

    public static Connection getConnection(String url, String username, String password) {
        Connection connection = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭操作后无用的类
     *
     * @param s
     * @param c
     * @param r
     */
    public static void clear(Statement s, Connection c, ResultSet r) {

        try {
            if (s != null) {
                s.close();
            }

            if (c != null) {
                c.close();
            }

            if (r != null) {
                r.close();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static JDBCUtils getInstance() {
        if (jdbcUtils == null) {
            jdbcUtils = new JDBCUtils();
        }
        return jdbcUtils;
    }

}
